package com.kingcore.director.calendar.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Event;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Observable;

import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.KeyStroke;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import wzw.swing.calendar.CalendarPanel;
import wzw.swing.table.PlainTable;
import wzw.swing.table.PlainTableModel;
import wzw.util.ComponentUtil;

import com.kingcore.director.base.ui.DirectorPanel;
import com.kingcore.director.base.ui.DirectorToolBar;
import com.kingcore.director.core.util.DirectorComponentUtils;
import com.kingcore.director.main.Main;
import com.kingcore.director.main.MainFrame;
import com.kingcore.director.reminder.ui.AwokeEditDialog;

public class CalendarMainPanel extends DirectorPanel implements MouseListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static final int MainSplitPane_Right_Width = Main.MainFrame_Size_Width - 221;
	private static final int MainSplitPane_LeftRight_Width = 188; //Main.MainFrame_Size_Width - 780;

	private static final int MainTable_Column_Index_Blank = 0;
	private static final int MainTable_Column_Index_Id = 1;
	private static final int MainTable_Column_Index_Title = 2;
	public static final int[] MainTable_Columns_Width = {0, 0, MainSplitPane_Right_Width};
	
	// log object
	private final static Logger log = Logger.getLogger(CalendarMainPanel.class);
	private MainFrame mainFrame = null; 

	public CalendarMainPanel(MainFrame mainFrame) {
		super(mainFrame);
		
		this.mainFrame = mainFrame;
		initializeInterface();
		
		try {
			fetchData();
		} catch (SQLException e) { 
			e.printStackTrace();
		}
	}

	private void initializeInterface(){
		// setTitle(" 阴历及节日软件 2008 beta1");
		// setIconImage(this.getToolkit().createImage("title.gif"));
		// setResizable(false);

		this.setLayout( new BorderLayout() );
		this.add( getToolBar(true), BorderLayout.NORTH);    //工具栏
		this.add( getMainSplitPane(), BorderLayout.CENTER); //内容区
		this.add( getStatusBar(true), BorderLayout.SOUTH);  //状态栏

//		this.addComponentListener(new ComponentAdapter() {
//			public void componentShown(ComponentEvent e) {
//				log.debug("panel:shown");
//				//refreshView();  // 不建议这调用，事件不可靠，在上层tabpage切换时候主动调用。
//				//setStatus( StatusBar_Index_One, currentStatusInfor);
//			}
//		});

		update(null, null);
    	
		constructAfter();
	}
	
	private JSplitPane mainSplitPane = null;
	private JSplitPane getMainSplitPane(){
		if (mainSplitPane==null) {
			mainSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, false);
					
			mainSplitPane.add( getLeftSplitPane(), JSplitPane.LEFT);
			mainSplitPane.add( getRightPanel(), JSplitPane.RIGHT);	

			// mainPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,false,getTree(),getTable());
			mainSplitPane.setDividerLocation( MainSplitPane_Right_Width );  //200);
		     
//			((JSplitPane)mainPanel).setBorder(null);
			// 设置JSplitPane是否可以展开或收起(如同文件总管一般)，设为true表示打开此功能。
			mainSplitPane.setOneTouchExpandable(true);
			// 设置分隔线宽度的大小，以pixel为计算单位。
			mainSplitPane.setDividerSize(5);
		}
		return mainSplitPane;
	}

	private JTabbedPane centerTabbedPane = null;
	private JTabbedPane getCenterTabbedPane(){
		if (centerTabbedPane==null) {
			centerTabbedPane = new JTabbedPane();
			centerTabbedPane.add( "  月   ", getCenterScrollPane() );
			centerTabbedPane.add( "  年   ", new JPanel() );
			
			centerTabbedPane.setEnabledAt(1, false);
		}
		return centerTabbedPane;
	}
	
	private JScrollPane centerScrollPane = null;
	/**
	 * This method initializes leftScrollPane
	 *
	 * @return javax.swing.JScrollPane
	 */
	private JScrollPane getCenterScrollPane() {
		if (centerScrollPane == null) {
	        // 设置文本区的滚动条
//	        int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
//	        int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
	        centerScrollPane = new JScrollPane( ); //, v, h

	        centerScrollPane.setViewportView( getCalendarSelectorPanel() );
//	        scrollPane.getVerticalScrollBar().setValue(0);
		}
		return centerScrollPane;
	}

	private CalendarSelectorPanel calendarSelectorPanel = null;
	private CalendarSelectorPanel getCalendarSelectorPanel() {
		if (calendarSelectorPanel==null) {
			calendarSelectorPanel = new CalendarSelectorPanel( this.mainFrame, this.getRightTopTable() );
			calendarSelectorPanel.setBounds(new java.awt.Rectangle(Math.max(0, (Main.MainFrame_Size_Width-600)/2),
												Math.max(0, (Main.MainFrame_Size_Height-30-600)/2),
												600,
												600));
			this.mainFrame.getLanguageManager().addObserver(calendarSelectorPanel);
		}
		return calendarSelectorPanel;
	}

	private JScrollPane rightTopScrollPane = null;
	private JScrollPane getRightTopScrollPane() {
		if (rightTopScrollPane == null) {
	        // 设置文本区的滚动条 
			rightTopScrollPane = new JScrollPane( ); //, v, h
			rightTopScrollPane.setViewportView( getRightTopTable() );
			//leftScrollPane.getVerticalScrollBar().setValue(0);
		}
		return rightTopScrollPane;
	}
 
	private JSplitPane leftSplitPane = null;
	private JSplitPane getLeftSplitPane() {
		if (leftSplitPane==null) {
			leftSplitPane = new JSplitPane();

			leftSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, false);					
			leftSplitPane.add( getLeftPanel(), JSplitPane.LEFT);
			leftSplitPane.add( getCenterTabbedPane(), JSplitPane.RIGHT);
			// mainPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,false,getTree(),getTable());
			leftSplitPane.setDividerLocation( MainSplitPane_LeftRight_Width );  //200);
//			((JSplitPane)mainPanel).setBorder(null);
			// 设置JSplitPane是否可以展开或收起(如同文件总管一般)，设为true表示打开此功能。
			leftSplitPane.setOneTouchExpandable(false);
			// 设置分隔线宽度的大小，以pixel为计算单位。
			leftSplitPane.setDividerSize(5);
			
		}
		return leftSplitPane;
	}

	private JPanel leftPanel = null; 
	private JPanel getLeftPanel() {
		if (leftPanel==null) {
			leftPanel = new JPanel();
			leftPanel.setLayout(null);
			leftPanel.add(getLeftTitleLabel(),null);
			leftPanel.add(getSmallCalendarPanel(),null);
		}
		return leftPanel;
	}

	private JLabel leftTitleLabel = null;
	private JLabel getLeftTitleLabel() {
		if(leftTitleLabel==null){
			leftTitleLabel = new JLabel(StringUtils.rightPad(" ", 2)
											+ "日历 "
											+ StringUtils.rightPad(" ", 32)
											+"今天 " );
			
			leftTitleLabel.setBounds(new java.awt.Rectangle(1,1,185,21));
		}
		return leftTitleLabel;
	}

	private CalendarPanel smallCalendarPanel = null;
	private CalendarPanel getSmallCalendarPanel() {
		if (smallCalendarPanel==null) {
			smallCalendarPanel = new CalendarPanel(true);
			smallCalendarPanel.setBounds(new java.awt.Rectangle(1,22,185,170));
		}
		return smallCalendarPanel;
	}

	private JPanel rightPanel = null;
	private JPanel getRightPanel() {
		if (rightPanel==null) {
			rightPanel = new JPanel();
			rightPanel.setLayout( new BorderLayout());
			rightPanel.add( getRightTopScrollPane() , BorderLayout.CENTER );
		}
		return rightPanel;
	}
	
	private PlainTable rightTopTable = null;
	private PlainTable getRightTopTable() {
		if(rightTopTable==null){
			rightTopTable = new PlainTable();

		    Object[][] data = {
		       //{"Jackson"}, {"Zachary"}
		    };
		    String[] headers = {
				      "编号", "", "我的日程"
		    };
		    
			DefaultTableModel dtm = new DefaultTableModel(1, 2);
		    dtm.setDataVector(data, headers);
		    PlainTableModel sorter = new PlainTableModel( dtm, rightTopTable.getTableHeader());
		    //sorter.setColumnClass(MainTable_Column_Index_NextTime, CodeNameBean.class);
		    rightTopTable.setModel(sorter);//dtm);
		    rightTopTable.setGridColor(Color.LIGHT_GRAY);  //Color.BLUE
		    rightTopTable.setRowSelectionAllowed(true);
		    //leftTableList.setRowSelectionInterval(1, 1);	
		    rightTopTable.setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); //.SINGLE_SELECTION

		    rightTopTable.setShowGrid(true);
		    rightTopTable.showZebraCross();
		    rightTopTable.addMouseListener( this );
		    
		    TableColumn tc = null;
		    TableColumnModel tcm = rightTopTable.getColumnModel(); 
	        for(int i=0; i < MainTable_Columns_Width.length; i++)   {
	            tc   =   tcm.getColumn(i);
	            tc.setPreferredWidth(MainTable_Columns_Width[i]); 
	        }

	        int[] cols = {MainTable_Column_Index_Blank,MainTable_Column_Index_Id};   //隐藏的列集合
	        DirectorComponentUtils.hideTableColumns(rightTopTable, cols); 
		    
		}
		return rightTopTable;
	}

	@Override
	public DirectorToolBar getToolBar() {
		if (this.toolBar==null) {
			this.toolBar = new CalendarToolBar( this );
			//this.setPreferredSize(new Dimension(20,25));
		}
		return this.toolBar; 
	}

	@Override
	 public void setStatusBarVisible(boolean isStatusBarShow) {
		if (isStatusBarShow) {
			this.add( getStatusBar(), BorderLayout.SOUTH);
		}else{
			this.remove( getStatusBar() );
		}
	}

	@Override
	public void setToolBarVisible(boolean isToolBarShow) {
		if (isToolBarShow) {
			this.add( getToolBar(), BorderLayout.NORTH);
		}else{
			this.remove( getToolBar() );
		}
	} 

	@Override
	public boolean fetchData() throws SQLException {
		//初始日程列表
		java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
		getCalendarSelectorPanel().fetchData(sdf.format(Calendar.getInstance().getTime()));

		return true;
	}

	@Override
	public boolean saveData() throws SQLException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void refreshView() {
		super.refreshView();
		
		setStatus( StatusBar_Index_One, currentStatusInfor);
		this.revalidate();
		
	}

	public void actionPerformed(ActionEvent e) {
		super.actionPerformed(e);
		
		Object obj=e.getSource();
		// toolBar
		if( obj==jpmi_MainTable_Edit){
			this.executeEditSelectedAwoke();
			
//		} else if( obj==jpmi_MainTable_Delete){
//			//executeDeleteSelectedAwoke();
//			
		} else if(obj ==jpmi_MainTable_Test){
			executeTestSelectedAwoke();
			
		}
		
	}

	private void executeTestSelectedAwoke() {
		String id = getSelectedId();
		if (id==null) {
			return;
		}
		
		this.mainFrame.getReminderMainPanel().executeTestSelectedAwoke(id);
	}

	private void executeEditSelectedAwoke() {
		String id = getSelectedId();
		if (id==null) {
			return;
		}
		AwokeEditDialog ap = new AwokeEditDialog(this.mainFrame, id);
		ComponentUtil.setLocationToCenter(this.mainFrame, ap);
		///ap.setModal(true); 
		ap.setVisible(true);
	}

	private String getSelectedId() {
	 	int row=getRightTopTable().getSelectedRow();
		if (row<0) {
			JOptionPane.showMessageDialog(this, msgDialog_plsSelectRow); //"请选择要修改的行！"
			return null;
		}
		String id= getRightTopTable().getValueAt( row, MainTable_Column_Index_Id).toString() ;
		return id;
	}

	@Override
	public void update(Observable o, Object arg) {
		super.update(o, arg);
		
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		Object obj = e.getSource() ;
		if(obj==getRightTopTable()){
			// 双击
			if(!e.isPopupTrigger() && e.getClickCount()==2) {
				executeEditSelectedAwoke();
			}
		}
	}

	@Override
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		Object obj = e.getSource() ;
		if(obj==getRightTopTable()){
			// 在Table上右击鼠标 
			if( e.getButton() == MouseEvent.BUTTON3 ) {	//显示弹出菜单 
				getPopupMenuForTable().setSelected(null);
				getPopupMenuForTable().show( e.getComponent(), e.getX(), e.getY() );
				
			}
		}
		
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	
	private JPopupMenu popupMenuForTable = null;	//JTable 的 JPopupMenu
	private JMenuItem jpmi_MainTable_Edit = null;
	private JMenuItem jpmi_MainTable_Delete = null;
	private JMenuItem jpmi_MainTable_Test = null;
	/**
	 * Table的弹出式菜单
	 */
	private JPopupMenu getPopupMenuForTable(){
		
		if(popupMenuForTable == null){
			popupMenuForTable = new JPopupMenu();
			
			jpmi_MainTable_Edit = new JMenuItem();
			jpmi_MainTable_Edit.setText("编辑提醒");
			jpmi_MainTable_Edit.addActionListener( this );
			jpmi_MainTable_Edit.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_M,Event.CTRL_MASK) );
//			jpmi_MainTable_Delete = new JMenuItem();
//			jpmi_MainTable_Delete.setText("删除提醒");
//			jpmi_MainTable_Delete.addActionListener( this );
//			jpmi_MainTable_Delete.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_D,Event.CTRL_MASK) );
			
			jpmi_MainTable_Test = new JMenuItem();
			jpmi_MainTable_Test.setText("测试提醒");
			jpmi_MainTable_Test.addActionListener( this );
			jpmi_MainTable_Test.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_T,Event.CTRL_MASK) );
			
			popupMenuForTable.add( jpmi_MainTable_Edit );
//			popupMenuForTable.add( jpmi_MainTable_Delete );
			popupMenuForTable.addSeparator();
			popupMenuForTable.add( jpmi_MainTable_Test );
			
		}
		
		return popupMenuForTable;
			
		
	}
 
}